package cn.ctvonline.android.kaopu.widget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.util.ToastUtil;

/**
 * Created by dujian on 15/12/8.
 */
public class FloatingManager {
    static final String TAG = FloatingManager.class + "";
    private WindowManager wm;
    private View view;// 浮动按钮
    private Context context;
    private Rect activeAreaRect;
    private boolean autoPosition = true;
    private WindowManager.LayoutParams params;

    public FloatingManager(Context context) {
        this.context = context;
    }

    private int paddingBottom;
    private int radius = 200;// 大小

    /**
     * 添加悬浮View
     *
     * @param paddingBottom 悬浮View与屏幕底部的距离
     */
    public void createFloatView(int paddingBottom) {
        this.paddingBottom = paddingBottom;
        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        view = LayoutInflater.from(context).inflate(R.layout.floating_view, null);
        params = new WindowManager.LayoutParams();


        params.type = WindowManager.LayoutParams.TYPE_PHONE;// 所有程序窗口的“基地”窗口，其他应用程序窗口都显示在它上面。
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.RGBA_8888;// 不设置这个弹出框的透明遮罩显示为黑色
        params.width = radius;
        params.height = radius;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        params.x = screenWidth - radius;
        params.y = screenHeight - radius - paddingBottom;
        view.setBackgroundColor(Color.TRANSPARENT);
        view.setVisibility(View.GONE);
        view.setOnTouchListener(new View.OnTouchListener() {
            // 触屏监听
            float lastX, lastY;
            int oldOffsetX, oldOffsetY;
            int tag = 0;// 悬浮球 所需成员变量

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getPointerCount() != 1) {
                    return false;
                }
                final int action = event.getAction();
                float x = event.getX();
                float y = event.getY();
                if (tag == 0) {
                    oldOffsetX = params.x; // 偏移量
                    oldOffsetY = params.y; // 偏移量
                }
                if (action == MotionEvent.ACTION_DOWN) {
                    lastX = x;
                    lastY = y;
                } else if (action == MotionEvent.ACTION_MOVE) {
                    params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动
                    params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动
                    tag = 1;
                    wm.updateViewLayout(view, params);
                } else if (action == MotionEvent.ACTION_UP) {
                    int newOffsetX = params.x;
                    int newOffsetY = params.y;
                    Log.i(TAG, "ACTION_UP:X=" + event.getX() + ",Y=" + event.getY() + ",newOffSetX=" + newOffsetX + ",newOffSetY=" + newOffsetY + ",screenWidth=" + screenWidth);
                    // 只要按钮一动位置不是很大,就认为是点击事件
                    if (Math.abs(oldOffsetX - newOffsetX) <= 20
                            && Math.abs(oldOffsetY - newOffsetY) <= 20) {
                        onFloatViewClick();
                    } else {
                        tag = 0;
                        //执行自动归位置
                        if (autoPosition) {
                            if (newOffsetX < screenWidth / 2) {
                                params.x = 0;
                            } else {
                                params.x = screenWidth;
                            }
                            params.y = newOffsetY;
                            wm.updateViewLayout(view, params);
                        }
                    }
                }
                return true;
            }
        });
        wm.addView(view, params);
        ToastUtil.show(context, "floating view created");
    }

    /**
     * 点击浮动按钮触发事件，需要override该方法
     */
    public void onFloatViewClick() {

    }

    /**
     * 指定活动区域
     *
     * @return
     */
    private boolean isOutOfActiveArea(int viewX, int viewY) {
        if (activeAreaRect != null) {
            if (viewX < activeAreaRect.left || viewX + view.getMeasuredWidth() > activeAreaRect.right
                    || viewY < activeAreaRect.top || viewY + view.getMeasuredHeight() > activeAreaRect.bottom)
                ;
            return true;
        }
        return false;
    }

    /**
     * 将悬浮View从WindowManager中移除，需要与createFloatView()成对出现
     */
    public void removeFloatView() {
        if (wm != null && view != null) {
            wm.removeViewImmediate(view);
            view = null;
            wm = null;
        }
    }

    public void setActiveAreaRect(Rect activeAreaRect) {
        this.activeAreaRect = activeAreaRect;
        params.x = activeAreaRect.right - radius;
        params.y = activeAreaRect.bottom - radius - paddingBottom;
        wm.updateViewLayout(view, params);
    }

    /**
     * 隐藏悬浮View
     */
    public void hideFloatView() {
        if (wm != null && view != null && view.isShown()) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 显示悬浮View
     */
    public void showFloatView() {
        if (wm != null && view != null && !view.isShown()) {
            view.setVisibility(View.VISIBLE);
        }
    }

}
